﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GMS.DataAccessDapper;
using GMS.IServices;
using GMS.Models.Entity;
using GMS.Models.SearchDto;
using GMS.Utils;

namespace GMS.Services
{
    public class RoleInfoService : IRoleInfoService
    {
        private readonly DapperUtil _dapper;

        public RoleInfoService(DapperUtil dapper)
        {
            _dapper = dapper;
        }

        public async Task<RoleInfo> GetSingleAsync(Guid id)
        {
            const string strSql = "select * from RoleInfo where Id=@id";
            return await _dapper.QuerySingleAsync<RoleInfo>(strSql, new { id });
        }

        public async Task<IEnumerable<RoleInfo>> GetMultipleAsync(RoleInfoSearchDto dto)
        {
            string strSql = "select * from RoleInfo where 1=1 ";
            if (!string.IsNullOrEmpty(dto.Name))
            {
                strSql += " and Name like @name";
                dto.Name = $"%{dto.Name}%";
            }

            if (!string.IsNullOrEmpty(dto.Key))
            {
                strSql += " and [Key] like @key";
                dto.Key = $"%{dto.Key}%";
            }

            strSql += " order by orderNum asc";
            return await _dapper.QueryMultipleAsync<RoleInfo>(strSql, dto);
        }

        public async Task<int> AddedAsync(RoleInfo role)
        {
            role.Id = GuidHelper.NewSeqGuid();
            EntityHelper<RoleInfo>.SetComm(role);
            string strSql =
                @"INSERT INTO dbo.RoleInfo(Id, Name, [Key], OrderNum, IsDisable, IsDel, CreateId, 
                     CreateBy, CreateTime,  Remark)Values(
                    @Id,@Name,@Key,@OrderNum,@IsDisable,@IsDel,@CreateId,@CreateBy,@CreateTime,@Remark
                    )";
            return await _dapper.ExecuteAsync(strSql, role);
        }

        public async Task<int> DeletedAsync(Guid id)
        {
            string strSql = "Delete From RoleInfo where Id=@id";
            return await _dapper.ExecuteAsync(strSql, new { id });
        }

        public async Task<int> UpdatedAsync(RoleInfo role)
        {
            string strSql = @"Update RoleInfo set  
                                        Id	=	@Id,
                                        IsDel	=	@IsDel,
                                        IsDisable	=	@IsDisable,
                                        [Key]	=	@Key,
                                        ModifyBy	=	'admin',
                                        ModifyId	=	'586D9525-8C4A-4994-8EA7-82C006EBD088',
                                        ModifyTime	=	getDate(),
                                        Name	=	@Name,
                                        OrderNum	=	@OrderNum,
                                        Remark	=	@Remark
                                        where Id=@Id";
            return await _dapper.ExecuteAsync(strSql, role);
        }
    }
}